<template>
	<view class="">
		<canvas canvas-id="posterCanvas" v-show="isCanvas"
			style="width: 750px;height:1000px;position: absolute;left: 0;top: 0;z-index: -1;"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				codeImg:""
			}
		},
		methods: {
			//生成小程序码
			getCreateXcxCode(data) {
				createXcxCode({
					goods_id: this.goods_id
				}).then(res => {
					console.log(res)
					this.codeImg = res.result;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: "none"
					})
				})
			},
			async generatePoster() {
				try {
					this.showShare = false;
					uni.showToast({
						icon: 'loading',
						mask: true,
						title: '海报生成中',
						duration: 5000
					});

					// const imgRes = await this.downloadImage(this.goodsInfo.banner_list[0].banner_img_path);
					const imgRes = await this.downloadImage("https://img-cdn.duobashuzi.com/xianggui/img/i_img_01.jpg"); 
					const imgRestwo = await this.downloadImage(this.codeImg);
					const imgPath = imgRes.tempFilePath;
					const imgPathtwo = imgRestwo.tempFilePath;

					setTimeout(() => {
						this.drawPoster(imgPath, imgPathtwo);
					}, 100);

				} catch (error) {
					console.error('生成海报时出错:', error);
					uni.showToast({
						title: '生成海报时出错，请重试',
						icon: 'none'
					});
				}

			},
			drawPoster(image, imgtwo) {
				// 绘制海报
				const posterCtx = uni.createCanvasContext('posterCanvas', this);
				const price = '￥' + this.goodsInfo.local_shop_price

				// 设置海报背景颜色
				posterCtx.setFillStyle('#ffffff');
				posterCtx.fillRect(0, 0, 750, 1000);
				// 绘制商品图片
				posterCtx.drawImage(image, 0, 0, 750, 750);

				// （商品标题）
				posterCtx.setFontSize(32);
				posterCtx.setFillStyle('#000000');
				// posterCtx.fillText(this.goodsInfo.product_name, 10, 770);
				this.wrapText(posterCtx, this.goodsInfo.product_name, 10, 780, 730, 40)
				// （价格）
				posterCtx.setFontSize(40);
				posterCtx.setFillStyle('#ff0000');
				posterCtx.fillText(price, 10, 900);

				// 绘制商品图片
				posterCtx.drawImage(imgtwo, 590, 840, 150, 150);
				// 将绘制的内容画到Canvas上

				posterCtx.draw(true, () => {
					console.log("触发成功")
					// 将Canvas内容转换为临时文件路径

					uni.canvasToTempFilePath({
						canvasId: 'posterCanvas',
						success: (res) => {

							console.log('海报生成成功', res.tempFilePath);
							wx.downloadFile({
								url: res.tempFilePath,
								success: (res) => {
									uni.hideToast()

									wx.showShareImageMenu({
										path: res.tempFilePath
									})
								}
							})
						},
						fail: (err) => {
							console.error('海报生成失败', err);
							uni.showToast({
								title: '海报生成失败，请重试',
								icon: 'none'
							});
						}
					}, this);
				});
			},
			//图片转为本地路径
			async downloadImage(url) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res);
							} else {
								reject(new Error('下载图片失败'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			//
			wrapText(ctx, text, x, y, maxWidth, lineHeight) {
				let currentLine = '';
				let lines = [];

				for (let i = 0; i < text.length; i++) {
					let testLine = currentLine + text[i];
					let metrics = ctx.measureText(testLine);
					let testWidth = metrics.width;

					if (testWidth > maxWidth && i > 0) {
						// 如果加上当前字符后超过了最大宽度，则换行
						lines.push(currentLine);
						currentLine = text[i]; // 当前字符作为新行的开始
						y += lineHeight;
					} else {
						// 否则继续添加到当前行
						currentLine = testLine;
					}
				}

				// 添加最后一行
				if (currentLine !== '') {
					lines.push(currentLine);
				}

				// 绘制所有行
				lines.forEach((line, index) => {
					console.log(`Drawing line ${index + 1}: "${line}" at (${x}, ${y + index * lineHeight})`);
					ctx.fillText(line, x, y + index * lineHeight);
				});
			},
		}
	}
</script>

<style>
</style>